const axios = require('axios');
const crypto = require('crypto');

// 测试配置
const BASE_URL = 'http://localhost:3000';
const WEBHOOK_URL = `${BASE_URL}/webhook/feishu`;
const ENCRYPT_KEY = 'QoMazhHf0AoOd2miHeoK7gT4aFASztop';

// 生成签名
function generateSignature(timestamp, nonce, body) {
  const stringToSign = timestamp + nonce + ENCRYPT_KEY + body;
  const hash = crypto.createHash('sha256');
  hash.update(stringToSign);
  return hash.digest('hex');
}

// 测试URL验证
async function testUrlVerification() {
  console.log('🧪 测试URL验证...');
  
  const challenge = 'test_challenge_' + Date.now();
  const payload = {
    type: 'url_verification',
    challenge: challenge
  };
  
  try {
    const response = await axios.post(WEBHOOK_URL, payload);
    console.log('✅ URL验证成功:', response.data);
    return response.data.challenge === challenge;
  } catch (error) {
    console.error('❌ URL验证失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试事件回调
async function testEventCallback() {
  console.log('🧪 测试事件回调...');
  
  const timestamp = Math.floor(Date.now() / 1000).toString();
  const nonce = 'test_nonce_' + Date.now();
  
  const payload = {
    type: 'event_callback',
    event: {
      type: 'message',
      event_id: 'test_event_' + Date.now(),
      event_type: 'message',
      message: {
        content: '测试消息',
        message_id: 'test_msg_' + Date.now()
      }
    }
  };
  
  const body = JSON.stringify(payload);
  const signature = generateSignature(timestamp, nonce, body);
  
  const headers = {
    'Content-Type': 'application/json',
    'X-Lark-Request-Timestamp': timestamp,
    'X-Lark-Request-Nonce': nonce,
    'X-Lark-Signature': signature
  };
  
  try {
    const response = await axios.post(WEBHOOK_URL, payload, { headers });
    console.log('✅ 事件回调成功:', response.data);
    return true;
  } catch (error) {
    console.error('❌ 事件回调失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试明文请求
async function testPlainRequest() {
  console.log('🧪 测试明文请求...');
  
  const payload = {
    type: 'test_plain',
    data: '这是明文测试数据'
  };
  
  try {
    const response = await axios.post(WEBHOOK_URL, payload);
    console.log('✅ 明文请求成功:', response.data);
    return true;
  } catch (error) {
    console.error('❌ 明文请求失败:', error.response?.data || error.message);
    return false;
  }
}

// 测试健康检查
async function testHealthCheck() {
  console.log('🧪 测试健康检查...');
  
  try {
    const response = await axios.get(`${BASE_URL}/webhook/health`);
    console.log('✅ 健康检查成功:', response.data);
    return response.data.code === 0;
  } catch (error) {
    console.error('❌ 健康检查失败:', error.response?.data || error.message);
    return false;
  }
}

// 运行所有测试
async function runAllTests() {
  console.log('🚀 开始运行飞书webhook测试...\n');
  
  const tests = [
    { name: '健康检查', fn: testHealthCheck },
    { name: 'URL验证', fn: testUrlVerification },
    { name: '事件回调', fn: testEventCallback },
    { name: '明文请求', fn: testPlainRequest }
  ];
  
  const results = [];
  
  for (const test of tests) {
    console.log(`\n📋 ${test.name}`);
    const result = await test.fn();
    results.push({ name: test.name, passed: result });
  }
  
  console.log('\n📊 测试结果汇总:');
  console.log('='.repeat(40));
  
  let passedCount = 0;
  for (const result of results) {
    const status = result.passed ? '✅ 通过' : '❌ 失败';
    console.log(`${result.name}: ${status}`);
    if (result.passed) passedCount++;
  }
  
  console.log('='.repeat(40));
  console.log(`总计: ${passedCount}/${results.length} 个测试通过`);
  
  if (passedCount === results.length) {
    console.log('🎉 所有测试通过！服务器运行正常。');
  } else {
    console.log('⚠️  部分测试失败，请检查服务器配置。');
  }
}

// 如果直接运行此文件，则执行测试
if (require.main === module) {
  runAllTests().catch(console.error);
}

module.exports = {
  testUrlVerification,
  testEventCallback,
  testPlainRequest,
  testHealthCheck,
  runAllTests
}; 